<template>
  <div class="analyse-group">
    <div class="group-list">
      <div class="search-header">
        <el-input v-model="searchInput" size="small" placeholder="输入搜索关键字" @keyup.13.native="onSearch">
          <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="searchInput.length"></i>
          <el-button type="primary" slot="append" icon="el-icon-search" @click="onSearch"></el-button>
        </el-input>
        <el-tooltip effect="dark" content="新建分组" placement="top">
          <el-button type="primary" class="add-btn" @click="editGroup('add')">
            <icon-svg name="iconGroup"></icon-svg>
          </el-button>
        </el-tooltip>
      </div>
      <el-collapse v-model="activeCollapse" accordion v-if="groupList.length || loading">
        <el-collapse-item v-for="(item, index) in groupList" :key="item.groupId" :name="item.groupId">
          <div slot="title" class="group-title">
            <i
              class="icon-toggle"
              :class="activeCollapse === item.groupId ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
            ></i>
            <el-tooltip effect="dark" :content="item.groupNm" placement="top-start">
              <span class="name">{{ item.groupNm }}</span>
            </el-tooltip>
            <el-popover placement="right-start" width="120" trigger="hover" popper-class="tag-group-handler">
              <ul>
                <li @click="handleAdd(item)"><i class="el-icon-circle-plus-outline"></i>添加漏斗分析</li>
                <template v-if="item.groupId">
                  <li @click="editGroup('edit', item)">
                    <icon-svg name="iconFacEdit" class="el-edit"></icon-svg>
                    编辑分组
                  </li>
                  <li @click="deleteGroup(item)">
                    <icon-svg name="iconDelete" class="el-delete"></icon-svg>
                    删除分组
                  </li>
                </template>
              </ul>
              <i class="el-icon-more group-handler" slot="reference"></i>
            </el-popover>
          </div>
          <div class="factory-list">
            <template v-if="item.page.results.length">
              <ul class="list-wrap">
                <li
                  class="list-item"
                  :class="{ 'is-active': tag.tagId === selectTag.tagId }"
                  v-for="tag in item.page.results"
                  :key="tag.tagId"
                  @click="selectItem(tag)"
                >
                  <icon-svg name="iconTag"></icon-svg>
                  <span class="list-name elli">{{ tag.funnelAnalysisName }}</span>
                </li>
              </ul>
              <el-pagination
                style="text-align: right"
                :current-page="item.page.params.currentPageNum"
                :page-size="item.page.params.pageSize"
                background
                layout="total, prev, pager, next"
                :total="item.page.totalSize"
                :pager-count="5"
                small
                @current-change="handleCurrentChange($event, index)"
              >
              </el-pagination>
            </template>
            <div class="no-record" v-else>
              <img src="~@/assets/img/no_records.png" /><br />
              暂无内容
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <div class="no-record" v-else>
        <img src="~@/assets/img/no_records.png" /><br />
        暂无内容
      </div>
    </div>
    <funnel-content
      ref="funnelContent"
      :config="selectTag"
      @callback="getList"
      @deleteFunnel="deleteFunnel"
    ></funnel-content>
    <tag-group ref="tagGroup" @callback="getGroupList"></tag-group>
  </div>
</template>

<script>
import funnelContent from './funnel-content'
export default {
  components: {
    funnelContent
  },
  data() {
    return {
      loading: true,
      activeCollapse: -1,
      groupList: [],
      searchInput: '',
      selectTag: {}
    }
  },
  created() {
    this.getGroupList()
  },
  watch: {
    activeCollapse() {
      // this.selectTag = {}
      this.getList()
    }
  },
  methods: {
    init() {
      this.getGroupList()
    },
    getGroupList() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagDerivedGroup/getAllGroup/3'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.groupList = [{ groupId: 0, groupNm: '默认分组' }, ...data.data]
          this.groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                ascs: [],
                descs: [],
                currentPageNum: 1,
                pageSize: 10,
                queryParams: {
                  groupId: item.groupId
                },
                descPriority: false
              },
              totalSize: 0
            }
          })
          if (this.selectTag.tagId) this.getList()
          else this.activeCollapse = 0
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getList() {
      const group = this.groupList.find(item => item.groupId === this.activeCollapse)
      const index = this.groupList.findIndex(item => item.groupId === this.activeCollapse)
      if (group) {
        let params = group.page.params
        if (this.searchInput.trim()) params.queryParams.funnelAnalysisName = this.searchInput.trim()
        else delete params.queryParams.funnelAnalysisName
        this.loading = true
        this.$ajax({
          url: this.$ajax.setUrl('funnelAnalysis/getFunnelInfo'),
          method: 'get',
          params: this.$ajax.setParams(group.page.params)
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.groupList[index].page.results = data.data.records
            this.groupList[index].page.totalSize = data.data.totalSize
            let maxPageNum = Math.ceil(data.data.totalSize / group.page.params.pageSize) || 1
            if (group.page.params.currentPageNum > maxPageNum) {
              group.page.params.currentPageNum = maxPageNum
              this.getList()
            }
            if (data.data.records.length && !this.selectTag.tagId) this.selectItem(data.data.records[0])
            else {
              if (this.selectTag.tagId) {
                const target = this.groupList[index].page.results.find(item => item.tagId === this.selectTag.tagId)
                if (target) this.selectTag = target
              }
            }
            this.$forceUpdate()
            this.$refs.funnelContent.loading = false
          } else {
            this.$message.error(data.data || data.msg)
          }
          this.loading = false
        })
      }
    },
    searchMyGroup() {
      this.$ajax({
        url: this.$ajax.setUrl('funnelAnalysis/searchMyAnalysis'),
        method: 'get',
        params: this.$ajax.setParams({
          tagNm: this.searchInput
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.groupList = data.data
          this.groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                ascs: [],
                descs: [],
                currentPageNum: 1,
                pageSize: 10,
                queryParams: {
                  groupId: item.groupId
                },
                descPriority: false
              },
              totalSize: 0
            }
          })
          if (!this.selectTag.tagId) this.activeCollapse = 0
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    onSearch() {
      this.activeCollapse = ''
      this.selectTag = {}
      if (!this.searchInput) {
        this.getGroupList()
      } else {
        this.searchMyGroup()
      }
    },
    clearSearch() {
      this.searchInput = ''
      this.selectTag = {}
      this.onSearch()
    },
    handleCurrentChange(num, index) {
      this.groupList[index].page.params.currentPageNum = num
      this.selectTag = {}
      this.getList()
    },
    selectItem(item) {
      this.selectTag = item
    },
    handleAdd(item) {
      this.$router.push({ name: 'funnel-config', query: { groupId: item.groupId } })
    },
    editGroup(type = 'add', item = {}) {
      this.$refs.tagGroup.showDialog({ type, groupId: item.groupId, groupNm: item.groupNm, groupType: 3 })
    },
    deleteGroup(item) {
      this.$confirm(`是否确认删除分组【${item.groupNm}】?`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astTagDerivedGroup/${item.groupId}`),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.getGroupList()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    deleteFunnel() {
      this.selectTag = {}
      this.getList()
    }
  }
}
</script>

<style lang="scss"></style>
